﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using Ext.Net;
using Ext.Net.MVC;
using SDSystem.Models;
using ComboBox = Ext.Net.ComboBox;
using MessageBox = Ext.Net.MessageBox;

namespace SDSystem.Controllers
{
    [DirectController]
    public class ServiceController : Controller
    {
        private static SDSystemEntities db=new SDSystemEntities();
        //
        // GET: /Service/

        #region Index
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult Index()
        {
            Session["includeInActive"] = false;
            Session["CharFilter"] = "";
            return View();
        }

        #endregion

        #region Create

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators")]
        public ActionResult Create()
        {
            ViewBag.HideTextBox = false;

            //ProgrammeId
            ViewBag.Programme = new List<ListItem>();
            var programmeList = db.Programmes.Where(p => p.IsActive == true);
            ViewBag.Programme =
                programmeList.ToList().Select(
                    m => new ListItem {Text = m.ProgrammeName, Value = m.ProgrammeId.ToString()});

            //ServiceType
            ViewBag.ServiceType = new List<ListItem>();
            var serviceType = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceType");
            if (serviceType != null)
                ViewBag.ServiceType =
                    serviceType.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //ServiceBenefitsCriterion
            ViewBag.ServiceBenefitsCriterion = new List<ListItem>();
            var serviceBenefitsCriterion = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceBenefitsCriterion");
            if (serviceBenefitsCriterion != null)
                ViewBag.ServiceBenefitsCriterion = serviceBenefitsCriterion.ReferenceDatas.ToList().Select(
                    ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            //ServiceDisability
            ViewBag.ServiceDisability = new List<ListItem>();
            var serviceDisability = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceDisability");
            if (serviceDisability != null)
                ViewBag.ServiceDisability =
                    serviceDisability.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //ServiceBarriers
            ViewBag.ServiceBarriers = new List<ListItem>();
            var serviceBarriers = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceBarriers");
            if (serviceBarriers != null)
                ViewBag.ServiceBarriers =
                    serviceBarriers.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //ServicePersonal
            ViewBag.ServicePersonal = new List<ListItem>();
            var servicePersonal = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServicePersonal");
            if (servicePersonal != null)
                ViewBag.ServicePersonal =
                    servicePersonal.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //ServiceEthnicity
            ViewBag.ServiceEthnicity = new List<ListItem>();
            var serviceEthnicity = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceEthnicity");
            if (serviceEthnicity != null)
                ViewBag.ServiceEthnicity =
                    serviceEthnicity.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //OtherServiceParticipation
            ViewBag.OtherServiceParticipation = new List<ListItem>();
            var otherServiceParticipation =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "OtherServiceParticipation");
            if (otherServiceParticipation != null)
                ViewBag.OtherServiceParticipation =
                    otherServiceParticipation.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //ClientSupportProcess
            ViewBag.ClientSupportProcess = new List<ListItem>();
            var clientSupportProcess =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientSupportProcess");
            if (clientSupportProcess != null)
                ViewBag.ClientSupportProcess =
                    clientSupportProcess.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //ClientOutcome
            ViewBag.ClientOutcome= new List<ListItem>();
            var clientOutcome =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientOutcome");
            if (clientOutcome != null)
                ViewBag.ClientOutcome =
                    clientOutcome.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //Intervention
            ViewBag.Intervention = new List<ListItem>();
            var intervention =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "Intervention");
            if (intervention != null)
                ViewBag.Intervention =
                    intervention.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //TargetClient
            ViewBag.TargetClient = new List<ListItem>();
            var targetClient =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "TargetClient");
            if (targetClient != null)
                ViewBag.TargetClient =
                    targetClient.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //ClientJourney
            ViewBag.ClientJourney = new List<ListItem>();
            var clientJourney =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientJourney");
            if (clientJourney != null)
                ViewBag.ClientJourney =
                    clientJourney.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //Accreditations
            ViewBag.Accreditations = new List<ListItem>();
            var accreditations =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "Accreditations");
            if (accreditations != null)
                ViewBag.Accreditations =
                    accreditations.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //OtherServices
            ViewBag.OtherServices = new List<ListItem>();
            var otherServices =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "OtherServices");
            if (otherServices != null)
                ViewBag.OtherServices =
                    otherServices.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //ReferralSources
            ViewBag.ReferralSources = new List<ListItem>();
            var referralSources =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ReferralSources");
            if (referralSources != null)
                ViewBag.ReferralSources =
                    referralSources.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //SupportCentres
            ViewBag.SupportCentres = new List<ListItem>();
            var supportCentres =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "SupportCentres");
            if (supportCentres != null)
                ViewBag.SupportCentres =
                    supportCentres.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            return View();
        }

        #endregion

        #region Save

        [HttpPost]
        public ActionResult Save(ServiceMaintain sv)
        {
            if (ModelState.IsValid)
            {
                #region Details2

                // ServiceBenefitsCriterion
                var tmp1 = X.GetCmp<MultiCombo>("ServiceBenefitsCriterion");
                //sv.ReferenceDatas.Clear();
                foreach (var item in tmp1.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ServiceDisability
                var tmp2 = X.GetCmp<MultiCombo>("ServiceDisability");
                foreach (var item in tmp2.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ServiceBarriers
                var tmp3 = X.GetCmp<MultiCombo>("ServiceBarriers");
                foreach (var item in tmp3.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ServicePersonal
                var tmp4 = X.GetCmp<MultiCombo>("ServicePersonal");
                foreach (var item in tmp4.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ServiceEthnicity
                var tmp5 = X.GetCmp<MultiCombo>("ServiceEthnicity");
                foreach (var item in tmp5.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //OtherServiceParticipation
                var tmp6 = X.GetCmp<MultiCombo>("OtherServiceParticipation");
                foreach (var item in tmp6.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }

                #endregion

                #region Details3

                //ClientSupportProcess
                var tmp7 = X.GetCmp<MultiCombo>("ClientSupportProcess");
                foreach (var item in tmp7.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ClientOutcome
                var tmp8 = X.GetCmp<MultiCombo>("ClientOutcome");
                foreach (var item in tmp8.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //Intervention
                var tmp9 = X.GetCmp<MultiCombo>("Intervention");
                foreach (var item in tmp9.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //TargetClient
                var tmp10 = X.GetCmp<MultiCombo>("TargetClient");
                foreach (var item in tmp10.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ClientJourney
                var tmp11 = X.GetCmp<MultiCombo>("ClientJourney");
                foreach (var item in tmp11.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //Accreditations
                var tmp12 = X.GetCmp<MultiCombo>("Accreditations");
                foreach (var item in tmp12.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //OtherServices
                var tmp13 = X.GetCmp<MultiCombo>("OtherServices");
                foreach (var item in tmp13.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ReferralSources
                var tmp14 = X.GetCmp<MultiCombo>("ReferralSources");
                foreach (var item in tmp14.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //SupportCentres
                var tmp15 = X.GetCmp<MultiCombo>("SupportCentres");
                foreach (var item in tmp15.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }

                #endregion

                #region Other

                //Get Service Extendable Value
                if (X.GetCmp<Checkbox>("checkServiceExtendable").Checked)
                {
                    int y, m;
                    y = Convert.ToInt32(X.GetCmp<NumberField>("yearEx").Value.ToString());
                    m = Convert.ToInt32(X.GetCmp<NumberField>("monthEx").Value.ToString());
                    sv.ServiceExtendable = 12*y + m;
                }
                //Get Service Time Limited Value
                if (X.GetCmp<Checkbox>("checkServiceTimeLimited").Checked)
                {
                    int y, m;
                    y = Convert.ToInt32(X.GetCmp<NumberField>("yearLi").Value.ToString());
                    m = Convert.ToInt32(X.GetCmp<NumberField>("monthLi").Value.ToString());
                    sv.ServiceTimeLimited = 12*y + m;
                }
                //Check Funding
                if (X.GetCmp<ComboBox>("subType").SelectedItem.Value == "Funding" &&
                    (String.IsNullOrEmpty(X.GetCmp<TextField>("FundingAmount").Text) ||
                     String.IsNullOrEmpty(X.GetCmp<TextField>("ContactLookup1").Text)))
                {
                    X.Msg.Notify("Non Sucess", "Create Service non success!").Show();
                    return this.FormPanel();
                }

                //Get Service Active Value
                sv.ServiceActive = X.GetCmp<Checkbox>("checkServiceActive").Checked;

                //Get Service Contract Staged Payment
                sv.ServiceStagePayment = X.GetCmp<Checkbox>("checkStagePayment").Checked;
                #endregion

                db.ServiceMaintains.AddObject(sv);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Create Service success!").Show();
                return this.FormPanel();
            }

            X.Msg.Notify("Non Sucess", "Create Service non success!").Show();
            return this.FormPanel();
        }

        #endregion

        #region Delete

        [DirectMethod]
        [AccessDeniedAuthorize(Roles = "administrators")]
        public ActionResult DeleteService(int id)
        {
            var sv = db.ServiceMaintains.SingleOrDefault(e => e.ServiceId == id);
            var store = X.GetCmp<Store>("ServiceStore");
            sv.ReferenceDatas.Clear();
            sv.Organisations.Clear();
            sv.Premises.Clear();
            db.ServiceMaintains.DeleteObject(sv);
            db.SaveChanges();
            store.Reload();
            return this.Direct();
        }

        #endregion

        #region Active

        [DirectMethod]
        [AccessDeniedAuthorize(Roles = "administrators")]
        public ActionResult ActiveService(int id)
        {
            var sv = db.ServiceMaintains.SingleOrDefault(e => e.ServiceId == id);
            var store = X.GetCmp<Store>("ServiceStore");
            if (sv.ServiceActive == false)
            {
                sv.ServiceActive = true;
                db.SaveChanges();
                store.Reload();
            }
            return this.Direct();
        }
        #endregion

        #region De-Active

        [DirectMethod]
        [AccessDeniedAuthorize(Roles = "administrators")]
        public ActionResult DeactiveService(int id)
        {
            var sv = db.ServiceMaintains.SingleOrDefault(e => e.ServiceId == id);
            var store = X.GetCmp<Store>("ServiceStore");
            sv.ServiceActive = false;
            db.SaveChanges();
            store.Reload();
            return this.Direct();
        }

        [DirectMethod]
        [AccessDeniedAuthorize(Roles = "administrators")]
        public ActionResult DeactiveServiceHaveCheck(int id)
        {
            var sv = db.ServiceMaintains.SingleOrDefault(e => e.ServiceId == id);
            sv.ServiceActive = false;
            db.SaveChanges();
            return this.Direct();
        }
        #endregion

        #region Detail
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult Detail(int id)
        {
            ServiceMaintain service = db.ServiceMaintains.Single(s => s.ServiceId == id);
            var contact = db.Contacts.SingleOrDefault(c => c.ContactId == service.ContactId);
            if (contact != null)
            {
                ViewBag.ContactTypes = contact.SureName;
            }
            var contact1 = db.Contacts.SingleOrDefault(c => c.ContactId == service.FundingContactDetail);
            if (contact1 != null)
            {
                ViewBag.FundingContact = contact1.SureName;
            }

            #region MultiCombo

            //ProgrammeId
            ViewBag.Programme = new List<ListItem>();
            ViewBag.Programme =
                db.Programmes.Where(m => m.IsActive == true).ToList().Select(
                    m => new ListItem { Text = m.ProgrammeName, Value = m.ProgrammeId.ToString() });
            ViewBag.selectedProgramme = service.Programme.ToString();
            //ServiceType
            ViewBag.ServiceType = new List<ListItem>();
            var serviceType = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceType");
            if (serviceType != null)
                ViewBag.ServiceType =
                    serviceType.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            //SelectedItems
            ViewBag.selectedServiceRef = new List<ListItem>();
            ViewBag.selectedServiceRef = service.ReferenceDatas.ToList().Select(
                ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            //ServiceBenefitsCriterion
            ViewBag.ServiceBenefitsCriterion = new List<ListItem>();
            var serviceBenefitsCriterion =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceBenefitsCriterion");
            if (serviceBenefitsCriterion != null)
            {
                ViewBag.ServiceBenefitsCriterion = serviceBenefitsCriterion.ReferenceDatas.ToList().Select(
                    ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            }


            //ServiceDisability
            ViewBag.ServiceDisability = new List<ListItem>();
            var serviceDisability = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceDisability");
            if (serviceDisability != null)
                ViewBag.ServiceDisability =
                    serviceDisability.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            //ServiceBarriers
            ViewBag.ServiceBarriers = new List<ListItem>();
            var serviceBarriers = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceBarriers");
            if (serviceBarriers != null)
                ViewBag.ServiceBarriers =
                    serviceBarriers.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            //ServicePersonal
            ViewBag.ServicePersonal = new List<ListItem>();
            var servicePersonal = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServicePersonal");
            if (servicePersonal != null)
                ViewBag.ServicePersonal =
                    servicePersonal.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            //ServiceEthnicity
            ViewBag.ServiceEthnicity = new List<ListItem>();
            var serviceEthnicity = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceEthnicity");
            if (serviceEthnicity != null)
                ViewBag.ServiceEthnicity =
                    serviceEthnicity.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            //OtherServiceParticipation
            ViewBag.OtherServiceParticipation = new List<ListItem>();
            var otherServiceParticipation =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "OtherServiceParticipation");
            if (otherServiceParticipation != null)
                ViewBag.OtherServiceParticipation =
                    otherServiceParticipation.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //ClientSupportProcess
            ViewBag.ClientSupportProcess = new List<ListItem>();
            var clientSupportProcess =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientSupportProcess");
            if (clientSupportProcess != null)
                ViewBag.ClientSupportProcess =
                    clientSupportProcess.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //ClientOutcome
            ViewBag.ClientOutcome = new List<ListItem>();
            var clientOutcome =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientOutcome");
            if (clientOutcome != null)
                ViewBag.ClientOutcome =
                    clientOutcome.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //Intervention
            ViewBag.Intervention = new List<ListItem>();
            var intervention =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "Intervention");
            if (intervention != null)
                ViewBag.Intervention =
                    intervention.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //TargetClient
            ViewBag.TargetClient = new List<ListItem>();
            var targetClient =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "TargetClient");
            if (targetClient != null)
                ViewBag.TargetClient =
                    targetClient.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //ClientJourney
            ViewBag.ClientJourney = new List<ListItem>();
            var clientJourney =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientJourney");
            if (clientJourney != null)
                ViewBag.ClientJourney =
                    clientJourney.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //Accreditations
            ViewBag.Accreditations = new List<ListItem>();
            var accreditations =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "Accreditations");
            if (accreditations != null)
                ViewBag.Accreditations =
                    accreditations.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //OtherServices
            ViewBag.OtherServices = new List<ListItem>();
            var otherServices =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "OtherServices");
            if (otherServices != null)
                ViewBag.OtherServices =
                    otherServices.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //ReferralSources
            ViewBag.ReferralSources = new List<ListItem>();
            var referralSources =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ReferralSources");
            if (referralSources != null)
                ViewBag.ReferralSources =
                    referralSources.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });
            //SupportCentres
            ViewBag.SupportCentres = new List<ListItem>();
            var supportCentres =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "SupportCentres");
            if (supportCentres != null)
                ViewBag.SupportCentres =
                    supportCentres.ReferenceDatas.ToList().Select(
                        ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            #endregion


            if (service.ServiceExtendable != null)
            {
                ViewBag.ServiceExtendable = true;
                ViewBag.YearEx = Convert.ToInt32(service.ServiceExtendable.Value) / 12;
                ViewBag.MonthEx = Convert.ToInt32(service.ServiceExtendable.Value) % 12;

            }
            else
            {
                ViewBag.ServiceExtendable = false;
                ViewBag.YearEx = 0;
                ViewBag.MonthEx = 0;
            }
            if (service.ServiceTimeLimited != null)
            {
                ViewBag.ServiceTimeLimited = true;
                ViewBag.YearLi = Convert.ToInt32(service.ServiceTimeLimited.Value) / 12;
                ViewBag.MonthLi = Convert.ToInt32(service.ServiceTimeLimited.Value) % 12;
            }
            else
            {
                ViewBag.ServiceTimeLimited = false;
                ViewBag.YearLi = 0;
                ViewBag.MonthLi = 0;
            }
            ViewBag.ServiceStagePayment = service.ServiceStagePayment;
            ViewBag.ServiceActive = service.ServiceActive;
            return View(service);
        }

        #endregion

        #region Edit
        [AccessDeniedAuthorize(Roles = "administrators")]
        public ActionResult Edit(int id)
        {
            ServiceMaintain service = db.ServiceMaintains.Single(s => s.ServiceId == id);
            var contact = db.Contacts.SingleOrDefault(c => c.ContactId == service.ContactId);
            ViewBag.CountOrgService = service.Organisations.Count();
            ViewBag.CountPreService = service.Premises.Count();
            Session["ssubtype"] = service.SubType;
            ViewBag.ServiceId=Session["sserviceId"] = service.ServiceId;
            service.SubType = null;
            if (contact != null)
            {
                ViewBag.ContactTypes = contact.SureName;
            }
            var contact1 = db.Contacts.SingleOrDefault(c => c.ContactId == service.FundingContactDetail);
            if (contact1 != null)
            {
                ViewBag.FundingContact = contact1.SureName;
            }

            #region MultiCombo

            //ProgrammeId
            ViewBag.Programme = new List<ListItem>();
            ViewBag.Programme =
                db.Programmes.Where(m => m.IsActive == true).ToList().Select(
                    m => new ListItem {Text = m.ProgrammeName, Value = m.ProgrammeId.ToString()});
            ViewBag.selectedProgramme = service.Programme.ToString();
            //ServiceType
            ViewBag.ServiceType = new List<ListItem>();
            var serviceType = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceType");
            if (serviceType != null)
                ViewBag.ServiceType =
                    serviceType.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //SelectedItems
            ViewBag.selectedServiceRef = new List<ListItem>();
            ViewBag.selectedServiceRef = service.ReferenceDatas.ToList().Select(
                ent => new ListItem { Text = ent.RefValue, Value = ent.RefId.ToString() });

            //ServiceBenefitsCriterion
            ViewBag.ServiceBenefitsCriterion = new List<ListItem>();
            var serviceBenefitsCriterion =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceBenefitsCriterion");
            if (serviceBenefitsCriterion != null)
            {
                ViewBag.ServiceBenefitsCriterion = serviceBenefitsCriterion.ReferenceDatas.ToList().Select(
                    ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            }
            

            //ServiceDisability
            ViewBag.ServiceDisability = new List<ListItem>();
            var serviceDisability = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceDisability");
            if (serviceDisability != null)
                ViewBag.ServiceDisability =
                    serviceDisability.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //ServiceBarriers
            ViewBag.ServiceBarriers = new List<ListItem>();
            var serviceBarriers = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceBarriers");
            if (serviceBarriers != null)
                ViewBag.ServiceBarriers =
                    serviceBarriers.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //ServicePersonal
            ViewBag.ServicePersonal = new List<ListItem>();
            var servicePersonal = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServicePersonal");
            if (servicePersonal != null)
                ViewBag.ServicePersonal =
                    servicePersonal.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //ServiceEthnicity
            ViewBag.ServiceEthnicity = new List<ListItem>();
            var serviceEthnicity = db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ServiceEthnicity");
            if (serviceEthnicity != null)
                ViewBag.ServiceEthnicity =
                    serviceEthnicity.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            //OtherServiceParticipation
            ViewBag.OtherServiceParticipation = new List<ListItem>();
            var otherServiceParticipation =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "OtherServiceParticipation");
            if (otherServiceParticipation != null)
                ViewBag.OtherServiceParticipation =
                    otherServiceParticipation.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //ClientSupportProcess
            ViewBag.ClientSupportProcess = new List<ListItem>();
            var clientSupportProcess =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientSupportProcess");
            if (clientSupportProcess != null)
                ViewBag.ClientSupportProcess =
                    clientSupportProcess.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //ClientOutcome
            ViewBag.ClientOutcome = new List<ListItem>();
            var clientOutcome =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientOutcome");
            if (clientOutcome != null)
                ViewBag.ClientOutcome =
                    clientOutcome.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //Intervention
            ViewBag.Intervention = new List<ListItem>();
            var intervention =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "Intervention");
            if (intervention != null)
                ViewBag.Intervention =
                    intervention.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //TargetClient
            ViewBag.TargetClient = new List<ListItem>();
            var targetClient =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "TargetClient");
            if (targetClient != null)
                ViewBag.TargetClient =
                    targetClient.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //ClientJourney
            ViewBag.ClientJourney = new List<ListItem>();
            var clientJourney =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ClientJourney");
            if (clientJourney != null)
                ViewBag.ClientJourney =
                    clientJourney.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //Accreditations
            ViewBag.Accreditations = new List<ListItem>();
            var accreditations =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "Accreditations");
            if (accreditations != null)
                ViewBag.Accreditations =
                    accreditations.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //OtherServices
            ViewBag.OtherServices = new List<ListItem>();
            var otherServices =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "OtherServices");
            if (otherServices != null)
                ViewBag.OtherServices =
                    otherServices.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //ReferralSources
            ViewBag.ReferralSources = new List<ListItem>();
            var referralSources =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "ReferralSources");
            if (referralSources != null)
                ViewBag.ReferralSources =
                    referralSources.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});
            //SupportCentres
            ViewBag.SupportCentres = new List<ListItem>();
            var supportCentres =
                db.ReferenceTypes.SingleOrDefault(ent => ent.RefTypeName == "SupportCentres");
            if (supportCentres != null)
                ViewBag.SupportCentres =
                    supportCentres.ReferenceDatas.ToList().Select(
                        ent => new ListItem {Text = ent.RefValue, Value = ent.RefId.ToString()});

            #endregion


            if (service.ServiceExtendable!=null)
            {
                ViewBag.ServiceExtendable = true;
                ViewBag.YearEx = Convert.ToInt32(service.ServiceExtendable.Value)/12;
                ViewBag.MonthEx = Convert.ToInt32(service.ServiceExtendable.Value)%12;
                
            }
            else
            {
                ViewBag.ServiceExtendable = false;
                ViewBag.YearEx = 0;
                ViewBag.MonthEx = 0;
            }
            if (service.ServiceTimeLimited != null)
            {
                ViewBag.ServiceTimeLimited = true;
                ViewBag.YearLi = Convert.ToInt32(service.ServiceTimeLimited.Value) / 12;
                ViewBag.MonthLi = Convert.ToInt32(service.ServiceTimeLimited.Value) % 12;
            }
            else
            {
                ViewBag.ServiceTimeLimited = false;
                ViewBag.YearLi = 0;
                ViewBag.MonthLi = 0;
            }
            ViewBag.ServiceStagePayment = service.ServiceStagePayment;
            ViewBag.ServiceActive = service.ServiceActive;
            return View(service);
        }

        #endregion

        #region Delete Reference Data

        public void DeleteRef(int id)
        {
            var sv = db.ServiceMaintains.SingleOrDefault(s => s.ServiceId == id);
            if (sv != null)
            {
                sv.ReferenceDatas.Clear();
                db.SaveChanges();
            }
            

        }

        #endregion

        #region EditCommit

        [HttpPost]
        public ActionResult EditCommit(ServiceMaintain sv)
        {
            
            
           var sv1 = db.ServiceMaintains.SingleOrDefault(s => s.ServiceId == sv.ServiceId);
            
            if (ModelState.IsValid)
            {
                DeleteRef(sv.ServiceId);
                //sv1.ReferenceDatas.Clear();
                if (Session["ssubtype"] != null && X.GetCmp<ComboBox>("subType").Value==null)
                {
                    sv.SubType = (string) Session["ssubtype"];
                }

                #region Details2

                
                // ServiceBenefitsCriterion
                var tmp1 = X.GetCmp<MultiCombo>("ServiceBenefitsCriterion");
                //sv.ReferenceDatas.Clear();
                foreach (var item in tmp1.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ServiceDisability
                var tmp2 = X.GetCmp<MultiCombo>("ServiceDisability");
                foreach (var item in tmp2.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ServiceBarriers
                var tmp3 = X.GetCmp<MultiCombo>("ServiceBarriers");
                foreach (var item in tmp3.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ServicePersonal
                var tmp4 = X.GetCmp<MultiCombo>("ServicePersonal");
                foreach (var item in tmp4.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ServiceEthnicity
                var tmp5 = X.GetCmp<MultiCombo>("ServiceEthnicity");
                foreach (var item in tmp5.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //OtherServiceParticipation
                var tmp6 = X.GetCmp<MultiCombo>("OtherServiceParticipation");
                foreach (var item in tmp6.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }

                #endregion

                #region Details3

                //ClientSupportProcess
                var tmp7 = X.GetCmp<MultiCombo>("ClientSupportProcess");
                foreach (var item in tmp7.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ClientOutcome
                var tmp8 = X.GetCmp<MultiCombo>("ClientOutcome");
                foreach (var item in tmp8.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //Intervention
                var tmp9 = X.GetCmp<MultiCombo>("Intervention");
                foreach (var item in tmp9.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //TargetClient
                var tmp10 = X.GetCmp<MultiCombo>("TargetClient");
                foreach (var item in tmp10.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ClientJourney
                var tmp11 = X.GetCmp<MultiCombo>("ClientJourney");
                foreach (var item in tmp11.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //Accreditations
                var tmp12 = X.GetCmp<MultiCombo>("Accreditations");
                foreach (var item in tmp12.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //OtherServices
                var tmp13 = X.GetCmp<MultiCombo>("OtherServices");
                foreach (var item in tmp13.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //ReferralSources
                var tmp14 = X.GetCmp<MultiCombo>("ReferralSources");
                foreach (var item in tmp14.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }
                //SupportCentres
                var tmp15 = X.GetCmp<MultiCombo>("SupportCentres");
                foreach (var item in tmp15.SelectedItems)
                {
                    var id = Convert.ToInt32(item.Value);
                    var refData = db.ReferenceDatas.Single(d => d.RefId == id);
                    sv.ReferenceDatas.Add(refData);
                }

                #endregion

                #region Other

                //Get Service Extendable Value
                if (X.GetCmp<Checkbox>("checkServiceExtendable").Checked)
                {
                    int y, m;
                    y = Convert.ToInt32(X.GetCmp<NumberField>("yearEx").Value.ToString());
                    m = Convert.ToInt32(X.GetCmp<NumberField>("monthEx").Value.ToString());
                    sv.ServiceExtendable = 12 * y + m;
                }
                //Get Service Time Limited Value
                if (X.GetCmp<Checkbox>("checkServiceTimeLimited").Checked)
                {
                    int y, m;
                    y = Convert.ToInt32(X.GetCmp<NumberField>("yearLi").Value.ToString());
                    m = Convert.ToInt32(X.GetCmp<NumberField>("monthLi").Value.ToString());
                    sv.ServiceTimeLimited = 12 * y + m;
                }
                //Check Funding
                if (X.GetCmp<ComboBox>("subType").SelectedItem.Value == "Funding" &&
                    (String.IsNullOrEmpty(X.GetCmp<TextField>("FundingAmount").Text) ||
                     String.IsNullOrEmpty(X.GetCmp<TextField>("ContactLookup1").Text)))
                {
                    X.Msg.Notify("Non Sucess", "Create Service non success!").Show();
                    return this.FormPanel();
                }

                //Get Service Active Value
                sv.ServiceActive = X.GetCmp<Checkbox>("checkServiceActive").Checked;

                //Get Service Contract Staged Payment
                sv.ServiceStagePayment = X.GetCmp<Checkbox>("checkStagePayment").Checked;

                #endregion
                db.ServiceMaintains.Detach(sv1);
                //db.ServiceMaintains.Attach(sv);
                db.ObjectStateManager.ChangeObjectState(sv, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Edit contact success!").Show();
            }
            //X.Msg.Alert("Contact", JSON.Serialize(contact)).Show();
            return this.FormPanel();
        }

        #endregion

        #region Include In-Active
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult IncludeInActive()
        {
            var store = X.GetCmp<Store>("ServiceStore");

            Session["includeInActive"] = !(bool) Session["includeInActive"];

            store.Reload();
            return this.Direct();
        }

        #endregion

        #region Char Filter

        [DirectMethod]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult CharFilter(string filterstring)
        {
            var store = X.GetCmp<Store>("ServiceStore");
            Session["CharFilter"] = filterstring;
            store.Reload();
            return this.Direct();
        }

        #endregion

        #region BindingStore

        [HttpGet]
        public ActionResult BindingStore(StoreRequestParameters parameters)
        {
            var queryStr = (from table1 in db.ServiceMaintains
                            join table2 in db.Contacts on table1.ContactId equals table2.ContactId
                            select new
                            {
                                table1.ServiceId,
                                table1.ServiceName,
                                table1.ServiceShortDes,
                                table1.ServiceType,
                                SureName = table2.SureName,
                                table1.ServiceActive

                            });

            bool includeInActive = (bool)Session["includeInActive"];
            string charFilter = (string)Session["CharFilter"];

            var result = queryStr.Where(ent => ((includeInActive || (bool) ent.ServiceActive)));
            if ("0".Equals(charFilter))
            {
                result = queryStr.Where(ent => ((includeInActive || (bool)ent.ServiceActive) &&
                   (ent.ServiceName.StartsWith("0") || ent.ServiceName.StartsWith("1") ||
                    ent.ServiceName.StartsWith("2") || ent.ServiceName.StartsWith("3") ||
                    ent.ServiceName.StartsWith("4") || ent.ServiceName.StartsWith("5") ||
                    ent.ServiceName.StartsWith("6") || ent.ServiceName.StartsWith("7") ||
                    ent.ServiceName.StartsWith("8") || ent.ServiceName.StartsWith("9")
                    )));
            }

            else
            {
                result = queryStr.Where(ent => ((includeInActive || (bool)ent.ServiceActive) && ent.ServiceName.StartsWith(charFilter)));

            }

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.ServiceId);
            }

            //var result1 = queryStr.Where(ent =>
            //                            (string.IsNullOrEmpty(ent.ServiceName) ||
            //                             ent.ServiceName.Contains(ent.ServiceName))
            //    ).ToList();

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData, result.Count());
        }

        #endregion

        #region PremiseService
        //Linked ServiceMaintains
        public ActionResult BindingStore1(StoreRequestParameters parameters)
        {
            var id = (int) Session["sserviceId"];
            var sv = db.ServiceMaintains.SingleOrDefault(s => s.ServiceId == id);

            var data1 = sv.Premises.ToList();
            var data = (from premises in data1
                        select new
                                    {
                                        premises.PremiseId,
                                        premises.PremiseName,
                                        premises.AddressLine1,
                                        premises.PhoneNumber,
                                        premises.ProjectCode,
                                    }

                        );

                var result = data.ToList();

                // Paging
                int limit = parameters.Limit;
                if ((parameters.Start + parameters.Limit) > result.Count)
                {
                    limit = result.Count - parameters.Start;
                }

                var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.GetRange(parameters.Start, limit);
                return this.Store(rangeData, result.Count);
            
        }

        //Not Linked ServiceMaintains
        public ActionResult BindingStore11(StoreRequestParameters parameters)
        {
            var id = (int)Session["sserviceId"];
            var sv = db.ServiceMaintains.SingleOrDefault(s => s.ServiceId == id);
            var data1 = sv.Premises;
            var arr1 = data1.Select(e => e.PremiseId);
            var data = (from premises in db.Premises
                        where !arr1.Contains(premises.PremiseId)
                        select new
                                   {
                                       premises.PremiseId,
                                       premises.PremiseName,
                                       premises.AddressLine1,
                                       premises.PhoneNumber,
                                       premises.ProjectCode,
                                   });
            var result = data.ToList();

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count)
            {
                limit = result.Count - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.GetRange(parameters.Start, limit);
            return this.Store(rangeData, result.Count);

        }

        //Add Linked ServiceMaitains
        [DirectMethod]
        public ActionResult AddPremiseLink(int id)
        {
            var store = X.GetCmp<Store>("PremisesListStore");
            var sid = (int)Session["sserviceId"];
            var sv = db.ServiceMaintains.SingleOrDefault(s => s.ServiceId == sid);
            var pr = db.Premises.SingleOrDefault(p => p.PremiseId == id);
            sv.Premises.Add(pr);
            db.SaveChanges();
            store.Reload();
            return this.Direct();
        }

        //Show List Premises Window
        public ActionResult ListPremises()
        {
            return View();
        }

        //Delete Premises Linked ServiceMaintains
        [DirectMethod]
        public ActionResult DeletePremises(int id)
        {
            var store = X.GetCmp<Store>("PremisesListStore");
            var sid = (int)Session["sserviceId"];
            var sv = db.ServiceMaintains.SingleOrDefault(s => s.ServiceId == sid);
            var pr = sv.Premises.SingleOrDefault(p => p.PremiseId == id);
            pr.ServiceMaintains.Remove(sv);
            db.SaveChanges();
            store.Reload();
            return this.Direct();
        }

        #endregion

        #region OrganisationService

        public ActionResult BindingStore2(StoreRequestParameters parameters)
        {
            var dataR = (from rl in db.OrganisationRoles
                         select new
                                    {
                                        rl.OrgId,
                                        rl.RolesName
                                    }).GroupBy(e => e.OrgId);
            var data3 = new List<OrganisationRole>();
            foreach (var items in dataR)
            {
                var arr = items.Select(e=>e.OrgId).ToArray();
                int dbid = arr[0];
                var itemsName=string.Join(",", items.Select(e => e.RolesName));
                var data3item = new OrganisationRole();
                data3item.OrgId = dbid;
                data3item.RolesName = itemsName;
                data3.Add(data3item);
            }
            var data4 = db.Organisations.ToList();
            var tmpdata = (from org in data4
                          join rl in data3 on org.OrgId equals rl.OrgId into orgGroup
                          from orl in orgGroup.DefaultIfEmpty()
                          select new
                          {
                              OrgId=org.OrgId,
                              OrgName=org.OrgName,
                              OrgShortDescription=org.OrgShortDescription,
                              RolesName=orl==null?"<null>":orl.RolesName
                          });
            var result = tmpdata.ToList();
            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count)
            {
                limit = result.Count - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.GetRange(parameters.Start, limit);
            return this.Store(rangeData, result.Count);
        }

        //Edit Organisation Role
        [DirectMethod]
        public ActionResult EditOrgRole(int id)
        {
            Organisation org = db.Organisations.SingleOrDefault(e => e.OrgId == id);
            ViewBag.ListRole = new List<ListItem>()
                                   {
                                       new ListItem{Text = "Funder",Value = "Funder"},
                                       new ListItem{Text="Lead",Value = "Lead"},
                                       new ListItem{Text = "Delivery",Value = "Delivery"},
                                       new ListItem{Text = "Auditor",Value = "Auditor"}
                                   };
            ViewBag.SelectedRole = new List<ListItem>();
            ViewBag.SelectedRole = org.OrganisationRoles.ToList().Select(e => new ListItem {Text = e.RolesName,Value = e.RolesName});
            return View(org);
        }
        //Save Organisation Role
        public ActionResult SaveOrgRole(Organisation org)
        {
            
            if(ModelState.IsValid)
            {
                var tmp = db.Organisations.SingleOrDefault(e => e.OrgId == org.OrgId);
                if (tmp != null && tmp.OrganisationRoles.Any())
                    tmp.OrganisationRoles.Clear();
                var tmp1 = X.GetCmp<MultiCombo>("listRoleOrg");
                foreach (var item in tmp1.SelectedItems)
                {
                    var orl = new OrganisationRole();
                    orl.OrgId = tmp.OrgId;
                    orl.RolesName = item.Value;
                    db.OrganisationRoles.AddObject(orl);
                }
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Edit role success!").Show();
            }
            return this.FormPanel();
        }

        #endregion

    }
}
